using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class SrcView : System.Web.UI.Page
{
    public bool showtitle = true;
    public String width = "100%";
    public String path;
    private String font;

    public void Page_Load(Object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            font = Request.QueryString["font"];
            if (font != null)
            {
                FontSize.SelectedIndex = (Int32.Parse(font) - 1);
            }
            else
            {
                font = (String)Session["SrcViewer.FontSize"];
                if (font != null)
                {
                    FontSize.SelectedIndex = (Int32.Parse(font.ToString()) - 1);
                }
                else
                {
                    FontSize.SelectedIndex = 2;
                }
            }
        }

        if (font == null)
        {
            font = FontSize.SelectedItem.Value;
        }

        MySourceCtrl.FontSize = Int32.Parse(FontSize.SelectedItem.Value);

        try
        {
            if (path == null)
                path = Request.QueryString["path"];

            string defaultFile = null;
            string defaultFilename = null;
            string displayFile = Request.QueryString["file"];
            string fullFile = string.Empty;

            if (displayFile != null)
            {
                // remove any querystring parameters from the displayFilename
                int start = displayFile.IndexOf('?');
                if (start != -1)
                    displayFile = displayFile.Substring(0, start);

                displayFile = displayFile.Replace(Request.ApplicationPath, "");
                if (displayFile.StartsWith("/"))
                    displayFile = displayFile.Remove(0, 1);

                fullFile = Path.Combine(Request.PhysicalApplicationPath, displayFile);
                Trace.Write("full", fullFile);
                MySourceCtrl.displayFilename = fullFile;
            }

            // see if there is a .src file for associated files
            string srcFile = Request.QueryString["src"];
            Trace.Write("src", srcFile);
            if (srcFile == null)
            {
                srcFile = displayFile + ".src";
            }
            else
            {
                displayFile = srcFile.Replace(".src", "");
                fullFile = Path.Combine(Request.PhysicalApplicationPath, displayFile);
            }

            // add the current page details
            AddFileRow(displayFile, fullFile, "Web Form", srcFile);

            // does a src file exist?
            string srcPath = Path.Combine(Request.PhysicalApplicationPath, srcFile);
            Trace.Write(srcPath, File.Exists(srcPath).ToString());
            if (!File.Exists(srcPath))
                return;

            FileStream fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            String line;

            // Loop through each line of the .src displayFile
            while ((line = sr.ReadLine()) != null)
            {
                Trace.Write("SrcViewer", "Reading in Line");

                String[] list = line.Split(new char[] { ':' });

                if (!(list.Length > 1))
                    break;

                // Grouping of displayFiles
                String sourcegroup = list[0];  
                String[] sourcelist = list[1].Split(new char[] { ',' });

                // Create the list of displayFile hyperlinks for this sourcegroup
                StringBuilder sb = new StringBuilder();
                Trace.Write("SrcViewer", "Source Group = " + sourcegroup);

                // iterate the files
                string sourcedisplayFile = string.Empty;
                for (int i = 0; i < sourcelist.Length; i++)
                {
                    sourcedisplayFile = sourcelist[i].Trim();
                    AddFileRow(sourcedisplayFile.Trim(),
                        Path.Combine(Request.PhysicalApplicationPath, sourcedisplayFile.Trim()), 
                        sourcegroup, srcFile);
                }
            }

            // If there was no match for the langpref cookie,
            // show the first displayFile of the first sourcegroup

            if (displayFile == null)
                MySourceCtrl.displayFilename = defaultFilename;

            fs.Close();

            if (showtitle != false)
            {
                if (displayFile != null)
                    Title.InnerHtml = displayFile;
                else if (defaultFile != null)
                    Title.InnerHtml = defaultFile;
            }
            else
                Title.InnerHtml = "";

        }
        catch (Exception exc)
        {
            Trace.Write("Exception", exc.ToString());
        }

        Session["SrcViewer.FontSize"] = font;
    }

    private bool IsCodeBehind(string displayFile)
    {
        string ext = new FileInfo(displayFile).Extension;
        return ext == ".vb" || ext == ".cs";
    }

    private void AddFileRow(string displayFile, string fullFile, string description, string srcFile)
    {
        // to maintain the file / code behind file order, if it's a code behind
        // file just strip the extension so that the code works the same as if
        // were a normal file. But only do this if it is a code behind file
        if (IsCodeBehind(displayFile))
        {
            string infront = fullFile.Substring(0, fullFile.Length - 3);
            if (File.Exists(infront))
            {
                displayFile = displayFile.Substring(0, displayFile.Length - 3);
                fullFile = fullFile.Substring(0, fullFile.Length - 3);
            }
        }

        // web form / user control - code behind has the same name plus extension
        // check for both vb and cs, assuming they'll only be one
        string otherFile = displayFile + ".vb";
        string otherFilePath = fullFile + ".vb";
        bool otherFileExists = true;
        StringBuilder otherFiles = new StringBuilder();

        Trace.Write(otherFilePath, File.Exists(otherFilePath).ToString());

        if (!File.Exists(otherFilePath))
        {
            otherFile = displayFile + ".cs";
            otherFilePath = fullFile + ".cs";

            otherFileExists = File.Exists(otherFilePath);
            Trace.Write(otherFilePath, File.Exists(otherFilePath).ToString());
        }
        
        HtmlTableRow displayFileRow = new HtmlTableRow();
        HtmlTableCell displayFileCell = new HtmlTableCell();
        displayFileCell.InnerHtml = String.Format("<b>{0}</b>", description);
        displayFileCell.Style.Add("padding-right", "10");
        displayFileRow.Cells.Add(displayFileCell);

        otherFiles.Append(String.Format("<a href='SrcView.aspx?file={0}&src={1}'>{2}</a>", displayFile, srcFile, displayFile));
        if (otherFileExists)
        {
            otherFiles.Append(", ");
            otherFiles.Append(String.Format("<a href='SrcView.aspx?file={0}&src={1}'>{2}</a>", otherFile, srcFile, otherFile));
        }
        displayFileCell = new HtmlTableCell();
        displayFileCell.InnerHtml = otherFiles.ToString();
        displayFileRow.Cells.Add(displayFileCell);
        SourceTable.Rows.Add(displayFileRow);
    }

    public void LinkButton_Click(Object sender, EventArgs e)
    {
        // do nothing
    }

    public void Size_Select(Object sender, EventArgs e)
    {
        MySourceCtrl.FontSize = Int32.Parse(FontSize.SelectedItem.Value);
        Session["SrcViewer.FontSize"] = FontSize.SelectedItem.Value.ToString();
    }

}
